package com.gidgabs.modules.api.service.impl;

import com.gidgabs.common.utils.DeleteType;
import com.gidgabs.common.utils.PaypalUtil;
import com.gidgabs.common.utils.ReturnJson;
import com.gidgabs.config.GidgabsContants;
import com.gidgabs.dto.TbOrderDataDto;
import com.gidgabs.dto.TbOrderDto;
import com.gidgabs.dto.TbOrderInfoDto;
import com.gidgabs.modules.api.service.TbOrderService;
import com.gidgabs.modules.dao.*;
import com.gidgabs.modules.entity.*;
import com.gidgabs.utils.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class TbOrderServiceImpl implements TbOrderService {
	@Autowired
	private TbOrderDao orderDao;

	@Autowired
	private TbOrderSuperDao orderSuperDao;

	@Autowired
	private TbOrderInfoDao orderInfoDao;

	@Autowired
	private TbShoppingCarDao shoppingCarDao;

    @Autowired
    private PaypalUtil paypalUtil;

    @Autowired
    private TbAddressDao tbAddressDao;


	@Override
	public TbOrderEntity queryObject(Integer id){
		return orderDao.queryObject(id);
	}
	
	@Override
	public List<TbOrderEntity> queryList(Map<String, Object> map){
		return orderDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return orderDao.queryTotal(map);
	}

	@Override
	public ReturnJson<TbOrderDataDto> save(TbUser tbUser, Integer[] shoppingCarIds) {
		//总数据集
		TbOrderDataDto tbOrderDataDto = new TbOrderDataDto();
		//子订单数据集
		List<TbOrderDto> tbOrderDtoList = new ArrayList<>();
		//创建父级订单
		TbOrderSuperEntity tbOrderSuperEntity = new TbOrderSuperEntity();
		tbOrderSuperEntity.setOrderCode(OrderUtil.StringtOrderNo());
		tbOrderSuperEntity.setCreateTime(new Date());
		//0 默认paypal
		tbOrderSuperEntity.setOrderPayType(0);
		tbOrderSuperEntity.setUserId(tbUser.getUserId());
		orderSuperDao.save(tbOrderSuperEntity);
		//所有订单总价
		int orderSuperCountMoney = 0;
		//循环查询购物车数据集
		List<TbShoppingCarEntity> tbShoppingCarEntityList = new ArrayList<>();
		for (int i = 0; i < shoppingCarIds.length; i++) {
			tbShoppingCarEntityList.add(shoppingCarDao.selectTbShoppingCarById(shoppingCarIds[i]));
		}
		//定义一个map集合用于分组 根据店铺id分组
		Map<Integer, List<TbShoppingCarEntity>> mapList = toGroup(tbShoppingCarEntityList);
		//遍历map集合
		for (Map.Entry<Integer, List<TbShoppingCarEntity>> m : mapList.entrySet())
		{
			//获取所有的值
			List<TbShoppingCarEntity> synList = m.getValue();
			//拿到商铺id
            int productMasterId = m.getKey();
			//循环获取所有产品价格总和
			int countMoney = 0;
			for (int i = 0; i < synList.size() ; i++) {
				TbShoppingCarEntity tbShoppingCarEntity = synList.get(i);
				countMoney += tbShoppingCarEntity.getPrice();
			}
            orderSuperCountMoney += countMoney;
			//创建子订单
			TbOrderEntity tbOrderEntity = new TbOrderEntity();
			tbOrderEntity.setOrderSuperId(tbOrderSuperEntity.getId());
			tbOrderEntity.setOrderCode(OrderUtil.StringtOrderNo());
			tbOrderEntity.setUserId(tbUser.getUserId());
			tbOrderEntity.setContact(tbUser.getUserName());
			tbOrderEntity.setPhone(tbUser.getMobile());//用户id
			//订单状态 1待支付 2 待接收 3 待评价 4 已退款
			tbOrderEntity.setOrderStatus(1);
			tbOrderEntity.setOrderSendPrice(0);
			tbOrderEntity.setOrderPrice(countMoney);
			tbOrderEntity.setOrderTotalPrice(countMoney);
			//默认paypal
			tbOrderEntity.setOrderpayType(0);
			tbOrderEntity.setCreateTime(new Date());
			tbOrderEntity.setDeleteType(DeleteType.NOT_DELETE.getKey());
            tbOrderEntity.setProductMasterId(productMasterId);
			orderDao.save(tbOrderEntity);
			//子订单数据对象
			TbOrderDto tbOrderDto = tbOrderEntity.toDto();
			//订单详细数据集
			List<TbOrderInfoDto> tbOrderInfoDtoList = new ArrayList<>();
			//循环每个店铺的产品 创建订单详细
			for (int i = 0; i < synList.size() ; i++) {
				TbShoppingCarEntity tbShoppingCarEntity = synList.get(i);
				//创建订单详细
				TbOrderInfoEntity tbOrderInfoEntity = new TbOrderInfoEntity();
				tbOrderInfoEntity.setOrderSunId(tbOrderEntity.getId());
				tbOrderInfoEntity.setOrderSuperId(tbOrderSuperEntity.getId());
				tbOrderInfoEntity.setAmount(tbShoppingCarEntity.getAmount());
				tbOrderInfoEntity.setCreateTime(new Date());
				tbOrderInfoEntity.setGraphicIntroductionUrl(tbShoppingCarEntity.getGraphicIntroductionUrl());
				tbOrderInfoEntity.setPrice(tbShoppingCarEntity.getPrice());
				tbOrderInfoEntity.setProductId(tbShoppingCarEntity.getProductId());
				tbOrderInfoEntity.setProductName(tbShoppingCarEntity.getProductName());
				orderInfoDao.save(tbOrderInfoEntity);
				tbOrderInfoDtoList.add(tbOrderInfoEntity.toDto());
			}
			//封装数据
			tbOrderDto.setTbOrderInfoDtoList(tbOrderInfoDtoList);
			tbOrderDtoList.add(tbOrderDto);
		}
		//封装所有订单价格总和
        tbOrderSuperEntity.setOrderPrice(orderSuperCountMoney);
        //封装至返回数据
        tbOrderDataDto.setTbOrderSuperDto(tbOrderSuperEntity.toDto());
		tbOrderDataDto.setTbOrderDtoList(tbOrderDtoList);
		//创建完成删除 购物车记录
		shoppingCarDao.deleteBatch(shoppingCarIds);
		return ReturnJson.success("下单成功",tbOrderDataDto);
	}

	private Map<Integer, List<TbShoppingCarEntity>> toGroup(List<TbShoppingCarEntity> tbShoppingCarEntityList){
		//定义一个map集合用于分组
		Map<Integer, List<TbShoppingCarEntity>> mapList = new HashMap<Integer, List<TbShoppingCarEntity>>();
		//遍历集合以ProductMasterId为键，以TbShoppingCarEntity为值保存到mapList中
		for (Iterator it = tbShoppingCarEntityList.iterator(); it.hasNext(); ) {
			//将循环读取的结果放入对象中
			TbShoppingCarEntity tbShoppingCarEntity = (TbShoppingCarEntity) it.next();
			//如果在这个map中包含有相同的键，这创建一个集合将其存起来
			if (mapList.containsKey(tbShoppingCarEntity.getProductMasterId())) {
				List<TbShoppingCarEntity> syn = mapList.get(tbShoppingCarEntity.getProductMasterId());
				syn.add(tbShoppingCarEntity);
				//如果没有包含相同的键，在创建一个集合保存数据
			} else {
				List<TbShoppingCarEntity> syns = new ArrayList<TbShoppingCarEntity>();
				syns.add(tbShoppingCarEntity);
				mapList.put(tbShoppingCarEntity.getProductMasterId(), syns);
			}
		}
		return mapList;
	}

	@Override
	public void update(TbOrderEntity order){
		orderDao.update(order);
	}
	
	@Override
	public void delete(Integer id){
		orderDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		orderDao.deleteBatch(ids);
	}

    @Override
    public ReturnJson<TbOrderDto> selectOrderById(Integer orderId) {
	    //查询子订单数据
        TbOrderEntity tbOrderEntity = orderDao.selectTbOrderById(orderId);
        //查询子订单详细数据列表
        TbOrderInfoEntity tbOrderInfoEntity = new TbOrderInfoEntity();
        tbOrderInfoEntity.setOrderSunId(orderId);
        List<TbOrderInfoEntity>  tbOrderInfoEntityList = orderInfoDao.selectTbOrderInfoByObj(tbOrderInfoEntity);
        List<TbOrderInfoDto> tbOrderInfoDtoList = new ArrayList<>();
        for (int i = 0; i < tbOrderInfoEntityList.size(); i++) {
            tbOrderInfoDtoList.add(tbOrderInfoEntityList.get(i).toDto());
        }
        TbOrderDto tbOrderDto = tbOrderEntity.toDto();
        tbOrderDto.setTbOrderInfoDtoList(tbOrderInfoDtoList);
        return ReturnJson.success("查询成功",tbOrderDto);
    }

    @Override
    public ReturnJson<String> payOrder(String orderCode, String[] messages, Integer money ,int addressId) {
        //判断是父级订单 还是子级订单
        TbOrderEntity tbOrderEntity = orderDao.selectTbOrderByCode(orderCode);
        TbOrderSuperEntity tbOrderSuperEntity = orderSuperDao.selectTbOrderSuperByCode(orderCode);
        String payUrl = "";
        //如果是子订单的支付
        if(tbOrderEntity != null){
            if (money!=null && money>0){
                payUrl = paypalUtil.pay(money / 100d, GidgabsContants.PAYPAL_ORDER_PRE + orderCode);
            }
            //添加订单地址
            tbOrderEntity.setAddressId(addressId);
            //支付时更新一次价格
			tbOrderEntity.setOrderPrice(money);
            orderDao.update(tbOrderEntity);
        }else if(tbOrderSuperEntity != null){
            if (money!=null && money>0){
                payUrl = paypalUtil.pay(money / 100d, GidgabsContants.PAYPAL_ORDER_SUPER_PRE + orderCode);
            }
			//支付时更新一次价格
			tbOrderSuperEntity.setOrderPrice(money);
            orderSuperDao.update(tbOrderSuperEntity);
            //根据父级订单查询子级订单列表 并循环添加订单地址
            TbOrderEntity tbOrder = new TbOrderEntity();
            tbOrder.setOrderSuperId(tbOrderSuperEntity.getId());
            List<TbOrderEntity> tbOrderEntityList = orderDao.selectTbOrderByObj(tbOrder);
            //循环修改子订单状态
            for (int i = 0; i < tbOrderEntityList.size(); i++) {
                TbOrderEntity orderEntity = tbOrderEntityList.get(i);
                //添加订单地址
                orderEntity.setAddressId(addressId);
                orderDao.update(tbOrder);
            }
        }else{
            return ReturnJson.fail("没有找到订单");
        }
        //添加订单留言
        for (int i = 0; i < messages.length; i++) {
            String[] datas = messages[i].split("\\|");
            String orderId = datas[0];
            String message = datas[1];
            TbOrderEntity tbOrderEntity1 = new TbOrderEntity();
            tbOrderEntity1.setId(Integer.valueOf(orderId));
            tbOrderEntity1.setBuyerMassage(message);
            orderDao.update(tbOrderEntity1);
        }
        return ReturnJson.success("支付地址",payUrl);
    }

	@Override
	public List<TbOrderEntity> selectOrderListByObj(TbOrderEntity tbOrderEntity) {
		return orderDao.selectTbOrderByObj(tbOrderEntity);
	}
}
